package com.beiing.tianshuai.tianshuai.message.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.CreateGroupFriendsAdapter;
import com.beiing.tianshuai.tianshuai.adapter.GroupMemberChoiceAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.ContactsBean;
import com.beiing.tianshuai.tianshuai.entity.CreateGroupBean;
import com.beiing.tianshuai.tianshuai.entity.GroupMemberChoiceBean;
import com.beiing.tianshuai.tianshuai.entity.MyFriendListBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.message.presenter.CreateGroupPresenter;
import com.beiing.tianshuai.tianshuai.message.view.CreateGroupViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.PersonalDataCardActivity;
import com.beiing.tianshuai.tianshuai.nim.session.SessionHelper;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.PinYinUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.SideLitterBarView;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

/**
 * 创建群聊界面
 *
 * @author Jinda Yang
 * @date 2018/5/31
 */
public class CreateGroupActivity extends BaseActivity implements CreateGroupViewImpl {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_btn_publish)
    TextView mSubmit;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTitle;
    @BindView(R.id.my_friends_list)
    ListView listView;
    @BindView(R.id.side_navigation)
    SideLitterBarView wordsNavigation;
    @BindView(R.id.fragment_container)
    FrameLayout mFragmentContainer;
    @BindView(R.id.tv_search_view)
    TextView mTvSearchView;
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.rv_choice_list)
    RecyclerView mRvChoiceList;

    public static final int MAX_MEMBER_NUMBER = 50;

    private Handler mHandler;

    private List<ContactsBean> mContactList;

    private String mUid;

    private CreateGroupFriendsAdapter mAdapter;

    private GroupMemberChoiceAdapter mRvAdapter;

    private CreateGroupPresenter mPresenter;

    private SearchFriendFragment mSearchFriendFragment;

    private boolean isSearching;

    /**
     * 已选择人数
     */
    private int mChoiceCount = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_create_group;
    }

    @Override
    protected void init() {
        Intent intent = getIntent();
        mUid = intent.getStringExtra("uid");
        mHandler = new Handler();
        mContactList = new ArrayList<>();
        initFragments();
        initToolbar();
        initAdapter();
        initRecyclerView();
        initListener();
        initPresenter();
    }

    private void initFragments() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        mSearchFriendFragment = SearchFriendFragment.newInstance(mContactList);
        transaction.setCustomAnimations(R.anim.translate_dialog_in, R.anim.translate_dialog_out);
        transaction.add(R.id.fragment_container, mSearchFriendFragment);
        transaction.hide(mSearchFriendFragment);
        transaction.commit();
    }

    private void initToolbar() {
        mSubmit.setVisibility(View.VISIBLE);
        mToolbarBack.setVisibility(View.VISIBLE);
        mToolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isSearching) {
                    finish();
                } else {
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.setCustomAnimations(R.anim.translate_dialog_in, R.anim.translate_dialog_out);
                    transaction.hide(mSearchFriendFragment);
                    transaction.commit();
                }
            }
        });

        mToolbarTitle.setText(
                MessageFormat.format("添加群成员（{0}/{1}）",
                        mChoiceCount, MAX_MEMBER_NUMBER)
        );

        mSubmit.setText("完成");
    }

    private void initListener() {
        // fragment回调
        mSearchFriendFragment.setSearchResultCheckListener(new SearchFriendFragment.SearchResultCheckListener() {
            @Override
            public void onSearchResultCheckListener(ContactsBean bean, int position) {
                checkFriendFromList(position, bean.isChecked(), bean);
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.setCustomAnimations(R.anim.translate_dialog_in, R.anim.translate_dialog_out);
                transaction.hide(mSearchFriendFragment);
                isSearching = false;
                transaction.commit();
            }
        });

        // 搜索
        mTvSearchView.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.setCustomAnimations(R.anim.translate_dialog_in, R.anim.translate_dialog_out);
                transaction.show(mSearchFriendFragment);
                isSearching = true;
                transaction.commit();
            }
        });

        // 完成
        mSubmit.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                // 初始化群组名称 默认以前3名的成员昵称组成
                List<GroupMemberChoiceBean> list = mRvAdapter.getList();

                // 初始化群介绍
                String desc = "还没有添加群简介";

                StringBuilder members = new StringBuilder();
                for (int i = 0; i < list.size(); i++) {
                    String uid = list.get(i).getUid();
                    if (i < list.size() - 1) {
                        members.append(uid).append(",");
                    } else {
                        members.append(uid);
                    }
                }

                /*
                 * 邀请成员加入群组的理由
                 */
                mPresenter.getCreateGroupRequest(
                        UserInfoBean.getUid(mContext),
                        "群聊",
                        desc,
                        "欢迎加入此群聊",
                        members.toString()
                );
            }
        });

        // 顶部成员选择
        mRvAdapter.setListener(new GroupMemberChoiceAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(int position, GroupMemberChoiceBean member) {
                mRvAdapter.removeData(position);
                int memberPosition = member.getPosition();
                mAdapter.unCheckBox(memberPosition);
            }
        });

        // 列表成员选择
        mAdapter.setListener(new CreateGroupFriendsAdapter.OnItemClick() {
            @Override
            public void onItemClickListener(int position, boolean isChecked, ContactsBean bean) {
                checkFriendFromList(position, isChecked, bean);
            }
        });

        // 点击好友
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mContactList != null) {
                    ContactsBean friend = mContactList.get(i);
                    String friendUid = friend.getUid();
                    Intent intent = new Intent(mContext, PersonalDataCardActivity.class);
                    intent.putExtra("uid", friendUid);
                    intent.putExtra("isFriend", true);
                    startActivity(intent);
                }
            }
        });

        // 快捷导航栏
        wordsNavigation.setListener(new SideLitterBarView.onWordsChangeListener() {
            @Override
            public void wordsChange(String words) {
                if (mContactList != null) {
                    updateWord(words);
                    updateListView(words);
                }
            }
        });

        // listView设置滑动监听
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (mContactList != null && mContactList.size() > 0) {
                    wordsNavigation.setTouchIndex(mContactList.get(i).getFirstLetter());
                }
            }
        });
    }

    private void checkFriendFromList(int position, boolean isChecked, ContactsBean bean) {
        if (isChecked) {

            // 判断当前人数是否大于50人，一次性最多邀请50人
            if (mChoiceCount >= MAX_MEMBER_NUMBER) {
                showShortText("最多选择50人");
                bean.setChecked(false);
                mAdapter.notifyDataSetChanged();
                return;
            }

            GroupMemberChoiceBean groupMemberChoiceBean = new GroupMemberChoiceBean();
            groupMemberChoiceBean.setAvatar(bean.getAvatar());
            groupMemberChoiceBean.setPosition(position);
            groupMemberChoiceBean.setNickName(bean.getName());
            groupMemberChoiceBean.setUid(bean.getUid());
            mRvAdapter.addData(groupMemberChoiceBean);
            mRvChoiceList.smoothScrollToPosition(mRvAdapter.getList().size());
            mChoiceCount++;

        } else {
            List<GroupMemberChoiceBean> list = mRvAdapter.getList();
            for (int i = 0; i < list.size(); i++) {
                GroupMemberChoiceBean choiceBean = list.get(i);
                if (choiceBean.getUid().equals(bean.getUid())) {
                    mRvAdapter.removeData(i);
                    mChoiceCount--;
                    break;
                }
            }
        }

        // 更新标题
        mToolbarTitle.setText(
                MessageFormat.format("添加群成员（{0}/{1}）",
                        mChoiceCount, MAX_MEMBER_NUMBER)
        );
    }

    private void initAdapter() {
        mAdapter = new CreateGroupFriendsAdapter(this, mContactList);
        listView.setAdapter(mAdapter);
    }

    private void initRecyclerView() {
        mRvAdapter = new GroupMemberChoiceAdapter(mContext);
        mRvChoiceList.setAdapter(mRvAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvChoiceList.setNestedScrollingEnabled(false);
        mRvChoiceList.setLayoutManager(linearLayoutManager);
    }

    private void initPresenter() {
        mPresenter = new CreateGroupPresenter(this);
        mPresenter.getMyFriendList(mUid);
    }

    private void updateWord(String words) {
        tvCenter.setText(words);
        tvCenter.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        //500ms后消失显示
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvCenter.setVisibility(View.GONE);
            }
        }, 500);
    }

    private void updateListView(String words) {
        for (int i = 0; i < mContactList.size(); i++) {
            //将手指按下的字母与列表中相同字母开头的项找出
            if (words.equals(mContactList.get(i).getFirstLetter())) {
                listView.setSelection(i);
                break;
            }
        }
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在努力加载，请稍后...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(MyFriendListBean bean) {
        List<MyFriendListBean.DataBean.NumberBean> friends = bean.getData().getNumber();
        if (friends.size() > 0) {
            mContactList.clear();
            for (MyFriendListBean.DataBean.NumberBean friend : friends) {
                try {
                    String name = friend.getName();
                    String uid = friend.getUid();
                    String avatar = friend.getPhoto();
                    String unit = friend.getUnit();
                    ContactsBean contactBean = new ContactsBean();
                    contactBean.setName(name);
                    contactBean.setAvatar(avatar);
                    contactBean.setUid(uid);
                    contactBean.setUnit(unit);
                    contactBean.setFirstLetter(PinYinUtils.getPinyin(name).substring(0, 1));
                    mContactList.add(contactBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Collections.sort(mContactList, new Comparator<ContactsBean>() {
                @Override
                public int compare(ContactsBean contactBean, ContactsBean t1) {
                    return contactBean.getFirstLetter().compareTo(t1.getFirstLetter());
                }
            });
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("网络异常");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * 创建群聊成功
     *
     * @param bean 新建群聊的信息
     */
    @Override
    public void createGroupSuccess(CreateGroupBean bean) {
        if (bean.getCode() == 200) {
            LogUtils.i("创建成功", "CreateSuccess");
            SessionHelper.startTeamSession(mContext, bean.getData().getNumber().getGroupid());
            finish();
        } else {
            CustomProgressDialog.stopLoading();
            showShortText("创建失败");
        }
    }

    @Override
    public void onBackPressed() {
        if (!isSearching) {
            super.onBackPressed();
        } else {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(R.anim.translate_dialog_in, R.anim.translate_dialog_out);
            transaction.hide(mSearchFriendFragment);
            transaction.commit();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CustomProgressDialog.stopLoading();
    }
}
